<template>
  <div class="tab-content blowing-detail">
    <BasicCard>
      <!-- <BasicVxeForm ref="formRef" :formOptions="formOptions"></BasicVxeForm> -->
      <BasicVxeTable v-bind="gridOptions">
        <template #stateCode="{ row }">
          <div class="flex flex-center-justify" style="width: 100%">
            <el-tag effect="dark" style="margin-top: 4px" :color="zhuanTai.color(row.stateCode)">
              {{ zhuanTai.text(row.stateCode, processName) }}
            </el-tag>
          </div>
        </template>
      </BasicVxeTable>
    </BasicCard>
  </div>
</template>
<script setup lang="ts">
  import { handleColumnsList } from '../../data'
  import { zhuanTai, valueZhuaneFloat } from '@/utils/custom/index'
  import {
    getwuLiaoAndJiTai,
    postShiSiXinXinList_qingHua,
    getShiShiZhuangTaiQuanJi,
    getZiDingYiBaoBiaos
  } from '@/api/shengChanJianShi'

  const props = defineProps<{
    processName: string
    statusCode: string
    detailName: string
  }>()

  const gridOptions = reactive<BasicGridProps>({
    extraConfig: {
      title: '',
      isCustom: false,
      isExport: true,
      isFilterAndSort: true
    }, // 拓展的配置
    id: `filter-detail-${props.statusCode}`, // id用于缓存,务必配置
    toolbarConfig: {}, // 工具栏
    height: 'auto',
    loading: true,
    exportConfig: {
      filename: '滤尘机台报表'
    }
  })

  const gongXuList = ref([])
  const jitaiArrayCode = ref([])

  // 获取自定义报表列表
  const customList = ref<any[]>([])
  const customDict = ref()
  const reportId = ref()
  const getCustomReportData = () => {
    getZiDingYiBaoBiaos({
      craftNodeName: props.detailName,
      pageName: props.detailName + '整机详情'
    }).then((res: any) => {
      customList.value = res
      customDict.value = customList.value.find((val) => {
        return val.defaultDisplayFlag === true
      })
      if (!customDict.value) {
        initData()
        return
      }
      reportId.value = customDict.value.id
      let itemArr = formattingData(customDict.value.customReportDetail, 'firstType')
      gridOptions.columns = handleColumnsList(itemArr)
    })
  }
  // 根据参数分组
  const formattingData = (arr, group_key) => {
    // 先定义一个空对象和空数组；
    let map = {}
    let res: any = []
    // 循环需要筛选的数组
    for (let i = 0; i < arr.length; i++) {
      let ai = arr[i]
      // 将需要筛选的属性的值作为新对象的键，并且判断是否已经存在
      if (!map[ai[group_key]]) {
        // 不存在的话就在map对象中创建一个属性的值作为键名，键值为空数组的新对象，并且把arr[i]放入
        map[ai[group_key]] = [ai]
      } else {
        // 如果已经存在就直接把arr[i]放入
        map[ai[group_key]].push(ai)
      }
    }
    // 循环后对map进行处理生成分组的数组
    Object.keys(map).forEach((key) => {
      res.push({ [group_key]: key, list: map[key] })
    })

    return res
  }

  const initData = () => {
    Promise.all([getStatusInfo(), getMaterialMachineInfo()]).then(() => {
      getList()
    })
  }

  // 获取采集所有参数
  const caiJiList = ref()
  const getStatusInfo = () => {
    return new Promise((resolve) => {
      getShiShiZhuangTaiQuanJi(props.detailName).then((res) => {
        caiJiList.value = res
        resolve(res)
      })
    })
  }

  // 获取物料和机台列表
  const backJson = ref()
  const getMaterialMachineInfo = () => {
    return new Promise((resolve) => {
      getwuLiaoAndJiTai(props.detailName).then((res) => {
        backJson.value = res
        if (backJson.value.length > 0) {
          let idArr: any = []
          let nameArr: any = []
          backJson.value.forEach((item, index) => {
            // 处理 item 自身的 text 和 id
            item.text = item.text || '未设置品种' // 简化空值判断
            item.id = item.id || `10000${index}`

            // 提取选中子节点的 id 和 text
            const checkedChildren = item.childNodes.filter((value) => value.check)
            idArr.push(...checkedChildren.map((child) => child.id))
            nameArr.push(...checkedChildren.map((child) => child.text))
          })
          gongXuList.value = backJson.value
          jitaiArrayCode.value = idArr

          resolve(res)
        }
      })
    })
  }

  // 获取列选择的参数
  const getList = () => {
    postShiSiXinXinList_qingHua(jitaiArrayCode.value).then((res: any) => {
      gridOptions.loading = false
      let tabTitles: any = []
      let tableData: any = []
      res.forEach((value) => {
        if (value.machineRealInfo !== null) {
          let values = {
            machineName: value.basic.machineName,
            materialName: value.basic.materialName,
            stateCode: value.basic.stateCode,
            ...value.machineRealInfo.realtime,
            ...value.machineRealInfo.process,
            ...value.machineRealInfo.settings
          }

          tableData.push(valueZhuaneFloat(values))
          if (customList.value.length != 0 && customDict.value !== undefined) return
          tabTitles = handleColumnsList(caiJiList.value, false)
        } else {
          let values = {
            machineName: value.basic.machineName,
            materialName: value.basic.materialName,
            stateCode: value.basic.stateCode
          }
          tableData.push(values)
        }
      })
      tableData.sort((a, b) => {
        return a.machineName - b.machineName
      })
      gridOptions.data = tableData
      if (customList.value.length != 0 && customDict.value !== undefined) return
      gridOptions.columns = [
        {
          title: '机台号',
          width: 100,
          field: 'machineName',
          fixed: 'left'
        },
        {
          title: '品种',
          field: 'materialName',
          width: 200,
          fixed: 'left'
        },
        {
          title: '状态',
          width: 110,
          slots: { default: 'stateCode' },
          field: 'stateCode',
          fixed: 'left'
        },
        ...tabTitles
      ]
    })
  }

  onMounted(() => {
    // getCustomReportData()
    initData()
  })
</script>
<style scoped lang="scss">
  .blowing-detail .el-card {
    height: calc(100% - 14px);
  }
</style>
